package com.firstclass.config;

import com.firstclass.interceptor.UserInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * mvc config
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /**
     * 支持项目中的接口跨域
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 项目中的所有接口都支持跨域
        registry.addMapping("/**")
                // 所有地址都可以访问，也可以配置具体地址
                .allowedOriginPatterns("*")
                // 是否允许请求带有验证信息
                .allowCredentials(true)
                // "Get" "POST" ...
                .allowedMethods("*")
                .allowedHeaders("*")
                // 跨域允许时间
                .maxAge(3600);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(userInterceptor())
                .addPathPatterns("/back/**")
                .excludePathPatterns("/back/user/login")
                .excludePathPatterns("/back/user/register")
                .excludePathPatterns("/back/user/getPW");
    }

    @Bean
    public UserInterceptor userInterceptor() {
        return new UserInterceptor();
    }

}
